import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Checkbox, FormInstance, Popover } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getAfterSaleList, auditStoreApplyInfo } from '@/services/shop/api';
import { history } from 'umi';
import PopoverContent from '@/components/PopoverContent/Index'
import { MsgType, showMsg, formatDate, isExits, isSupportSticky } from '@/utils/utils';
import './style.less'
import BreadcrumbDept from '@/components/BreadcrumbDept';
import PermissionControl from '@/components/PermissionControl';
import Auditing from '@/components/Auditing';

interface IndexProps {
  location?: any;
}

const Index: React.FC<IndexProps> = (props) => {
  const { location } = props;
  const { query } = location;
  const { order_id, way, apply_status } = query;

  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const [line, setLine] = useState<number>(-1);
  const [loading, setLoading] = useState<boolean>(false);
  const auditingRef = useRef();

  const columns: ProColumns<SHOPAPI.ShopAfterSale>[] = [
    {
      title: '申请单号',
      dataIndex: 'apply_id',
      className: 'wordbreak',
      width: 170,
      fieldProps: {
        placeholder: '输入申请单号',
      }
    },
    {
      title: '原订单号',
      dataIndex: 'order_id',
      width: 150,
      fieldProps: {
        placeholder: '输入订单编号',
      }
    },
    {
      title: '申请时间',
      dataIndex: 'apply_time',
      valueType: 'dateTime',
      width: 140,
      search: false,
    },
    {
      title: '申请时间',
      dataIndex: 'create_date',
      valueType: 'date',
      width: 140,
      hideInTable: true,
    },
    {
      title: '用户账号',
      dataIndex: 'user_name',
      width: 120,
      fieldProps: {
        placeholder: '收货人姓名/手机号码',
      }
    },
    {
      title: '订单退款',
      align: 'right',
      valueType: 'money',
      dataIndex: 'refund_fee',
      width: 90,
      search: false
    },
    {
      title: '退快递费',
      align: 'right',
      valueType: 'money',
      dataIndex: 'mail_price',
      width: 90,
      search: false
    },
    {
      title: '售后方式',
      dataIndex: 'way',
      valueType: 'select',
      width: 60,
      valueEnum: {
        1: '退货',
        2: '退款'
      }
    },
    {
      title: '申请状态',
      dataIndex: 'apply_status',
      valueType: 'select',
      width: 60,
      valueEnum: {
        U: '待处理',
        H: '受理中',
        S: '已完成',
        F: '已拒绝',
        C: '已撤销',
      },
      search: false,
    },

    {
      title: '售后状态',
      dataIndex: 'after_sales_status',
      search: false,
      width: 60,
      valueType: 'select',
      valueEnum: {
        W: '待收货',
        I: '退款中',
        R: '已退款',
        M: '待收货'
      },
      render: (val, record) => {
        if (record.after_sales_status === 'M') {
          return record.return_way === '1' ? '待寄回' : '待送回'
        }
        return val;
      }
    },
    {
      title: '搜索结果不包括',
      dataIndex: 'not_include',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Checkbox.Group
            options={
              [
                {
                  label: '已完成',
                  value: 'S'
                },
                {
                  label: '已拒绝',
                  value: 'F'
                }
              ]
            }
          />
        );
      }
    },
    {
      title: '操作',
      align: 'center',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : '',
      width: 120,
      valueType: 'option',
      render: (_, record, index) => [
        isExits('600613002') &&
        <a onClick={() => {
          history.push({
            pathname: record.way === '2' ? '/shop/after-sale/refund' : '/shop/after-sale/return-goods',
            query: {
              apply_id: record.apply_id,
              order_id: record.order_id
            }
          })
        }}>查看</a>,

        record.apply_status === 'U' && <PermissionControl action_id="600613004" key="reject">
            <Popover 
              placement="topRight"
              visible={visible && line === index}
              // onVisibleChange={setVisible}
              content={ <PopoverContent 
                confirmText="确认" 
                onCancel={() => {
                  setVisible(false);
                  setLine(-1);
                }}
                loading={loading}
                onConfirm={ async (value: string) => {
                  setLoading(true);
                  const data = {
                    apply_id: record.apply_id,
                    audit: 'FAIL',
                    refuse_reason: value,
                    Action_Id: '600613004'
                  };
                  auditingRef?.current?.onSign({sign_no: record.apply_id, sign_string: JSON.stringify(data), title: `小程序${record.way === '1' ? '退货' : '退款'}审批`}, async() => {
                    await auditStoreApplyInfo(data).then(res => {
                      showMsg('已审批', MsgType.SUCCESS);
                      actionRef.current?.reload();
                      setVisible(false);
                      setLoading(false);
                      setLine(-1);
                    }).catch(error => {
                      setLoading(false);
                      showMsg(error?.data?.errmsg);
                    });
                  })
              }} /> }
              trigger="click">
              <Auditing
                ref={auditingRef}
                loading={loading}
                module='MR'
                onLoading={e => setLoading(e)}
                onError={() => {
                  setLoading(false);
                }}
                onClick={() => {
                  setVisible(true);
                  setLine(index);
                }}
                _html={<a>拒绝</a>}
              />
            </Popover>
          </PermissionControl>
      ]
    }
  ];

  useEffect(() => {
    if (order_id || way || apply_status) {
      formRef.current?.setFieldsValue({
        order_id,
        way,
        apply_status
      });
      formRef.current?.submit();
    }
  }, [order_id, way, apply_status])

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<SHOPAPI.ShopAfterSale, SHOPAPI.ShopAfterSale & COMMON.PageParams>
        actionRef={actionRef}
        className="shop-after-sale-table"
        bordered
        formRef={formRef}
        rowKey="apply_id"
        search={{
          span: 6,
          labelWidth: 110,
          collapsed: false,
          collapseRender: () => '',
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [<PermissionControl key="search" action_id="600613001">{dom}</PermissionControl>];
          }
        }}
       
        request={async (params) => {
          console.log(params)
          try {
            if (params.create_date) {
              params.create_date = formatDate(params.create_date, 'YYYY-MM-DD');
            }
            if (apply_status) {
              params.apply_status = apply_status
            }
            const data: SHOPAPI.ShopAfterSaleList = await getAfterSaleList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        options={false}
        columns={columns}
        scroll={{
          // x: 1100
        }}
        pagination={{
          showQuickJumper: true
        }}
      />
    </PageContainer>
  );
};

export default Index;
